package com.diandian.backend.entrance.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.diandian.backend.entrance.constants.EntranceConstant;
import com.diandian.backend.entrance.dto.ClientPermissionCacheDataDTO;
import com.diandian.backend.entrance.service.ClientSecretCheckService;
import com.diandian.backend.entrance.service.RouterService;
import com.diandian.base.boot.starter.exception.DefaultException;
import com.diandian.base.boot.starter.response.BaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 入口服务
 */
@RestController
@RequestMapping("/middle/platform")
public class EntranceController {

    private static final Logger logger = LoggerFactory.getLogger(EntranceController.class);

    @Autowired
    private RouterService routerService;

    @Autowired
    private ClientSecretCheckService clientSecretCheckService;

    /**
     * 统一入口API
     * @param clientKey 客户端key
     * @param clientSecret 客户端密钥
     * @param version 接口版本，v1版本无签名验证，v2版本含签名验证，签名规则：MD5(appKey + appSecret + yyyy-MM-dd HH:mm:ss + JSON.toJSONString(param) + appSecret)
     * @param time 签名时间，格式：yyyy-MM-dd HH:mm:ss
     * @param sign 签名
     * @param cmd 要执行的指令
     * @param data 接口数据
     * @return
     * @throws Exception
     */
    @PostMapping("/router")
    public BaseResult router(@RequestHeader(value = "clientKey") String clientKey,
                             @RequestHeader(value = "clientSecret")  String clientSecret,
                             @RequestHeader(value = "version", required = false)  String version,
                             @RequestHeader(value = "time", required = false)  String time,
                             @RequestHeader(value = "sign", required = false)  String sign,
                             @RequestHeader(value = "cmd") String cmd,
                             @RequestBody(required = false) JSONObject data) throws Exception {

        String dataStr = data == null ? "" : data.toString();
        logger.info("接收到请求，clientKey:{}, clientSecret:{}, cmd:{}, data:{}", clientKey, clientSecret, cmd, dataStr);

        // 校验客户端合法性和有效性：多版本接口
        ClientPermissionCacheDataDTO clientPermissionCacheDataDTO;
        if(version == null || "".equals(version) || EntranceConstant.INTERFACE_VERSION_FIRST.equals(version)){
            clientPermissionCacheDataDTO = clientSecretCheckService.checkV1(clientKey, clientSecret, cmd);
        } else if(EntranceConstant.INTERFACE_VERSION_SECOND.equals(version)){
            clientPermissionCacheDataDTO = clientSecretCheckService.checkV2(clientKey, clientSecret, cmd, data.toJSONString(), time, sign);
        } else {
            throw new DefaultException("暂不支持此接口版本");
        }
//        logger.info("客户端合法性和有效性校验通过，信息： {}", JSON.toJSONString(clientPermissionCacheDataDTO));

        // 执行后续处理
        Object result = routerService.execute(clientPermissionCacheDataDTO, clientKey, clientSecret, cmd, data);

        // 统一返回结构
        return new BaseResult(0, "success", result);
    }

}
